<template>
    <div class="use-next-layout group/body">
        <BaHeader/>
        <div style="height: 100vh">
            <div class="login">
                <div class="login-box">
                    <div class="head">
                        <img src="~assets/login-header.png" alt=""/>
                    </div>
                    <div class="form">
                        <div class="content" >
                            <el-form @keyup.enter="onLoginSubmitPre()" ref="loginRef" :rules="loginRules"  size="large" :model="state.login">
                                <el-form-item prop="username">
                                    <el-input
                                        ref="usernameRef"
                                        type="text"
                                        clearable
                                        v-model="state.login.username"
                                        placeholder="请输入手机号"
                                    >
                                        <template #prefix>
                                            <Icon name="fa fa-user" class="form-item-icon" size="16"
                                                  color="var(--el-input-icon-color)"/>
                                        </template>
                                    </el-input>
                                </el-form-item>
                                <el-form-item prop="password">
                                    <el-input
                                        ref="passwordRef"
                                        v-model="state.login.password"
                                        type="password"
                                        placeholder="请输入密码"
                                        show-password
                                    >
                                        <template #prefix>
                                            <Icon name="fa fa-unlock-alt" class="form-item-icon" size="16"
                                                  color="var(--el-input-icon-color)"/>
                                        </template>
                                    </el-input>
                                </el-form-item>
                                <el-checkbox v-model="state.login.keep" :label="t('login.Hold session')"
                                             size="default"></el-checkbox>
                                <el-form-item>
                                    <el-button
                                        @click="onLoginSubmitPre"
                                        :loading="state.loading.login"
                                        round
                                        type="primary"
                                        size="large"
                                        class="zent-btn-primary zent-btn-large zent-btn-block zent-btn-border-transparent zent-btn login-container__btn js-login-verify-code-btn clickable-button-disabled "
                                        :class="state.loading.login?'zent-btn-disabled':''"
                                    >
                                        登录
                                    </el-button>
                                    <p style="font-size: 18px;color: #999999;margin: 20px auto;cursor: pointer" @click.stop="switchTab('captchaLogin')">二维码登录</p>
                                </el-form-item>
                            </el-form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="account" v-if="false">
            <div class="account__container">
                <div class="account__container__left">
                    <div class="login-container" v-if="state.tab == 'mobileLogin'">
                        <div class="switch-type" @click="switchTab('captchaLogin')">
                            <p class="switch-type__tip">
                                <img
                                    src="https://img01.yzcdn.cn//public_files/982ce7a51441adc9bdad447d53d3de0d.png!origin.png"/>
                                <span>扫码登录更便捷</span>
                            </p>
                            <img class="js-tab-scan-code-login" src="~/assets/icons/toogle_qr_code-8761ac48da.svg"/>
                        </div>
                        <div class="login-container__header">
                            <span class="js-tab-captcha-login" :class="state.actionType == 'captcha' ? 'bold' : ''"
                                  @click="switchLoginType('captcha')">验证码登录</span>
                            <span class="js-tab-password-login" :class="state.actionType == 'password' ? 'bold' : ''"
                                  @click="switchLoginType('password')">密码登录</span>
                        </div>
                        <el-form class="zent-form zent-form--horizontal" data-cp-zv="2.3.0"  ref="loginRef"
                                 @keyup.enter="onLoginSubmitPre"  :rules="loginRules"  :model="state.login">
                            <div class="account-input">
                                <div class="zent-input-wrapper zent-input--size-normal account-input__input"
                                     data-zv="v10.0.11">
                                    <input placeholder="请输入手机号"
                                           maxlength="11"
                                           type="text"
                                           class="zent-input"
                                           data-zv="v10.0.11"
                                           v-model="state.login.username"
                                    />
                                </div>
                                <p class="account-input__warning">验证完成后，可使用该手机号登录或找回密码</p>
                            </div>
                            <div class="account-password" v-if="state.actionType == 'password'">
                                <div class="zent-input-wrapper zent-input--size-normal account-password__input account-password__input--show-forget"
                                     data-zv="v10.0.11">
                                    <input name="password" :type="passType?'password':'text'"  v-model="state.login.password" placeholder="输入登录密码"
                                           class="zent-input" data-zv="v10.0.11" value="">
                                </div>
                                <span  class="account-password__icon  forget-pass-icon" :class="passType?'account-password__icon--open':'account-password__icon--hide'" @click="showPass"></span>
                                <a class="account-password__forget-password" href="/retrieve-pass">忘记密码</a>
                                <p class="account-password__error"></p>
                            </div>
                            <div class="account-captcha" v-else>
                                <div class="zent-input-wrapper zent-input--size-normal account-captcha__input"
                                     data-zv="v10.0.11">
                                    <input  v-model="state.login.smscode"
                                            name="captcha"
                                            maxlength="6"
                                            type="text"
                                            placeholder="输入短信验证码"
                                            autocomplete="off"
                                            class="zent-input"
                                            data-zv="v10.0.11"
                                    />
                                </div>
                                <div class="account-captcha__btn js-get-identify-code">获取验证码</div>
                                <p class="account-captcha__warn"></p>
                            </div>
                            <div class="login-container__auto">
                                <el-checkbox v-model="state.login.keep" :label="'保持登录'" size="default"></el-checkbox>
                                <client-only v-if="false">
                                    <div
                                        v-if="state.accountVerificationType.length > 0"
                                        @click="state.showRetrievePasswordDialog = true"
                                        class="forgot-password"
                                    >
                                        忘记密码？
                                    </div>
                                </client-only>
                                <div>
                                    <label class="zent-checkbox-wrap login-container__protocol__check shake-motion"
                                           data-zv="v10.0.11">
                                        <span class="zent-checkbox" data-zv="v10.0.11">
                                            <span class="zent-checkbox-inner" data-zv="v10.0.11"></span>
                                            <input type="checkbox" data-zv="v10.0.11"/>
                                        </span>
                                        <div class="zent-checkbox-label" data-zv="v10.0.11">
                                            阅读并同意
                                            <a target="_blank" rel="noopener noreferrer"
                                               href="/examples/agreement">用户协议</a>
                                            <span>、</span>
                                            <a target="_blank" rel="noopener noreferrer"
                                               href="/examples/statement">隐私声明</a>
                                        </div>
                                    </label>
                                </div>
                                <el-button
                                    @click="onLoginSubmitPre"
                                    :loading="state.loading.login"
                                    round
                                    type="primary"
                                    size="large"
                                    class="zent-btn-primary zent-btn-large zent-btn-block zent-btn-border-transparent zent-btn login-container__btn js-login-verify-code-btn clickable-button-disabled "
                                    :class="state.loading.login?'zent-btn-disabled':''"
                                    data-zv="v10.0.11">
                                    <span data-zv="v10.0.11">登&nbsp;录</span>
                                </el-button>
                                <div class="login-container__links">
                                    <div class="login-container__links__actions">
                                        没有账号，<a class="js-goto-register-btn" href="/register">免费注册</a>
                                    </div>
                                </div>
                            </div>
                        </el-form>
                    </div>
                    <div class="login-qrcode" v-if="state.tab == 'captchaLogin'">
                        <div class="switch-type" @click="switchTab('mobileLogin')">
                            <p class="switch-type__tip">
                                <span>账号登录</span>
                            </p>
                            <img class="js-tab-scan-code-login" src="~/assets/icons/toogle_pc_code-efa39f77bd.png"/>
                        </div>
                        <div class="login-qrcode__container">
                            <div class="login-qrcode__container__qrcode">
                                <img
                                    src=""
                                    alt="http://passport.youzan.com/scan-login?token=YZ7F4620EA57B9411CA6982AD2B1E8462B&amp;fromSource=SOURCE_PC"
                                />
                                <div class="warning warning--show">
                                    <i class="zenticon zenticon-refresh refresh__icon" data-zv="v10.0.11"></i>
                                    <p>二维码已失效</p>
                                </div>
                            </div>
                            <div class="login-qrcode__container__banner">
                                <div class="zent-swiper" data-zv="v10.0.11">
                                    <div class="zent-swiper__container" data-zv="v10.0.11">
                                        <img
                                            src="https://img01.yzcdn.cn/public_files/7d4b1fdf8259420218aacaa82af59dbe.png!large.png">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="login-qrcode__register">没有账号，<a class="login-qrcode__register__link"
                                                                        href="/register">免费注册</a></div>
                    </div>
                </div>
                <a class="account__container__right" href="/" target="_blank" rel="noopener noreferrer">
                    <img class="account__container__right__cover" src="https://iph.href.lu/380x520" alt=""
                         loading="lazy"/>
                </a>
            </div>
        </div>
        <BaFooter/>
    </div>
</template>
<script setup lang="ts">
import type {FormItemRule, FormInstance} from 'element-plus'
import {sendEms, sendSms} from '~/api/common'
import {checkIn, retrievePassword} from '~/api/user/index'
import clickCaptcha from '~/composables/clickCaptcha'
import {useI18n} from 'vue-i18n'

const {t} = useI18n()
let timer: NodeJS.Timeout
useSeoMeta({
    title: '用户登录',
})
definePageMeta({
    layout: false,
    name: 'userLogin1',
    noNeedLogin: true,
})

interface State {
    tab: 'mobileLogin' | 'captchaLogin' | 'passwordLogin' | 'Register'
    actionType: 'mobile' | 'captcha' | 'password'
    loading: {
        login: boolean
        register: boolean
        retrievePassword: boolean
    }
    login: {
        username: string
        password: string
        captchaInfo: string
        captchaId: string
        smscode:string
        keep: boolean
    }
    register: {
        registerType: 'email' | 'mobile'
        username: string
        password: string
        mobile: string
        email: string
        captcha: string
    }
    retrieveDialogWidth: number
    showRetrievePasswordDialog: boolean
    accountVerificationType: string[]
    retrievePasswordForm: {
        type: 'email' | 'mobile'
        account: string
        captcha: string
        password: string
    }
    sendCaptchaLoading: boolean
    codeSendCountdown: number
    to: string
}
const passType=ref(false)
const showPass=()=>{
    passType.value=!passType.value
}
const route = useRoute()
const userInfo = useUserInfo()
const siteConfig = useSiteConfig()
const memberCenter = useMemberCenter()
const loginRef = ref<FormInstance>()
const registerRef = ref<FormInstance>()
const retrieveRef = ref<FormInstance>()
const state: State = reactive({
    tab: 'captchaLogin',
    actionType: 'password',
    loading: {
        login: false,
        register: false,
        retrievePassword: false,
    },
    login: {
        username: '18888888888',
        password: 'admin123',
        smscode:'',
        captchaInfo: '',
        captchaId: uuid(),
        keep: false,
    },
    register: {
        registerType: 'email',
        username: '',
        password: '',
        mobile: '',
        email: '',
        captcha: '',
    },
    retrieveDialogWidth: 36,
    showRetrievePasswordDialog: false,
    accountVerificationType: [],
    retrievePasswordForm: {
        type: 'email',
        account: '',
        captcha: '',
        password: '',
    },
    sendCaptchaLoading: false,
    codeSendCountdown: 0,
    to: route.query.to as string,
})

const loginRules: Partial<Record<string, FormItemRule[]>> = reactive({
    username: [buildValidatorData({name: 'required', title: t('login.User name')})],
    password: [buildValidatorData({
        name: 'required',
        title: t('login.Password')
    }), buildValidatorData({name: 'password'})],
})
const switchLoginType = (loginType: any) => {
    state.actionType = loginType
    state.register.mobile = ''
    state.register.email = ''
}
const registerRules: Partial<Record<string, FormItemRule[]>> = reactive({
    username: [
        buildValidatorData({name: 'required', title: t('login.User name')}),
        buildValidatorData({name: 'account', title: t('login.User name')}),
    ],
    email: [
        buildValidatorData({name: 'required', title: t('login.Email')}),
        buildValidatorData({name: 'email', title: t('login.Email')}),
    ],
    password: [buildValidatorData({
        name: 'required',
        title: t('login.Password')
    }), buildValidatorData({name: 'password'})],
    mobile: [buildValidatorData({
        name: 'required',
        title: t('login.Mobile')
    }), buildValidatorData({name: 'mobile'})],
    captcha: [buildValidatorData({name: 'required', title: t('login.Captcha')})],
})

const retrieveRules: Partial<Record<string, FormItemRule[]>> = reactive({
    account: [buildValidatorData({name: 'required', title: t('login.Account name')})],
    captcha: [buildValidatorData({name: 'required', title: t('login.Captcha')})],
    password: [buildValidatorData({
        name: 'required',
        title: t('login.Password')
    }), buildValidatorData({name: 'password'})],
})

const onLoginSubmitPre = () => {
    loginRef.value?.validate((valid) => {
        if (!valid) return
        clickCaptcha(state.login.captchaId, (captchaInfo: string) => onLoginSubmit(captchaInfo))
    })
}
const onLoginSubmit = (captchaInfo: string) => {
    state.loading.login = true
    state.login.captchaInfo = captchaInfo
    checkIn('post', {...state.login, tab: state.tab.toLocaleLowerCase()})
        .then((res) => {
            if (res.code != 1) return
            userInfo.dataFill(res.data.userInfo)
            if (state.to) return (location.href = state.to)
            navigateTo({path: res.data.routePath})
        })
        .finally(() => {
            state.loading.login = false
        })
}

const switchTab = (type: State['tab']) => {
    state.tab = type
    if (type == 'Login') {
        loginRef.value?.resetFields()
        loginRef.value?.clearValidate()
    } else {
        registerRef.value?.resetFields()
        registerRef.value?.clearValidate()
    }
}

const sendRegisterCaptchaPre = () => {
    if (state.codeSendCountdown > 0) return
    registerRef.value?.validateField([state.register.registerType, 'username', 'password']).then((valid) => {
        if (!valid) return
        clickCaptcha(state.login.captchaId, (captchaInfo: string) => sendRegisterCaptcha(captchaInfo))
    })
}
const sendRegisterCaptcha = (captchaInfo: string) => {
    state.sendCaptchaLoading = true
    const func = state.register.registerType == 'email' ? sendEms : sendSms
    func(state.register[state.register.registerType], 'user_register', {
        captchaInfo,
        captchaId: state.login.captchaId,
    })
        .then((res) => {
            if (res.code == 1) startTiming(60)
        })
        .finally(() => {
            state.sendCaptchaLoading = false
        })
}

const sendRetrieveCaptchaPre = () => {
    if (state.codeSendCountdown > 0) return
    retrieveRef.value?.validateField('account').then((valid) => {
        if (!valid) return
        clickCaptcha(state.login.captchaId, (captchaInfo: string) => sendRetrieveCaptcha(captchaInfo))
    })
}
const sendRetrieveCaptcha = (captchaInfo: string) => {
    state.sendCaptchaLoading = true
    const func = state.retrievePasswordForm.type == 'email' ? sendEms : sendSms
    func(state.retrievePasswordForm.account, 'user_retrieve_pwd', {
        captchaInfo,
        captchaId: state.login.captchaId,
    })
        .then((res) => {
            if (res.code == 1) startTiming(60)
        })
        .finally(() => {
            state.sendCaptchaLoading = false
        })
}

const onRegisterSubmit = (registerRef: FormInstance | undefined = undefined) => {
    if (!registerRef) return
    registerRef.validate((valid) => {
        if (!valid) return
        state.loading.register = true
        checkIn('post', {...state.register, tab: state.tab.toLocaleLowerCase()})
            .then((res) => {
                if (res.code != 1) return
                userInfo.dataFill(res.data.userInfo)
                navigateTo({path: res.data.routePath})
            })
            .finally(() => {
                state.loading.register = false
            })
    })
}

const onSubmitRetrieve = (retrieveRef: FormInstance | undefined = undefined) => {
    if (!retrieveRef) return
    retrieveRef.validate((valid) => {
        if (valid) {
            state.loading.retrievePassword = true
            retrievePassword({...state.retrievePasswordForm})
                .then((res) => {
                    if (res.code == 1) {
                        state.showRetrievePasswordDialog = false
                        endTiming()
                        onResetForm(retrieveRef)
                    }
                })
                .finally(() => {
                    state.loading.retrievePassword = false
                })
        }
    })
}

const startTiming = (seconds: number) => {
    state.codeSendCountdown = seconds
    timer = setInterval(() => {
        state.codeSendCountdown--
        if (state.codeSendCountdown <= 0) {
            endTiming()
        }
    }, 1000)
}
const endTiming = () => {
    state.codeSendCountdown = 0
    clearInterval(timer)
}

const dialogSize = () => {
    if (import.meta.server) return
    let clientWidth = document.documentElement.clientWidth
    let width = 36
    if (clientWidth <= 790) {
        width = 92
    } else if (clientWidth <= 910) {
        width = 56
    } else if (clientWidth <= 1260) {
        width = 46
    }
    state.retrieveDialogWidth = width
}

checkIn('get').then((res) => {
    if (res.code != 1) return
    state.accountVerificationType = res.data.accountVerificationType
    state.retrievePasswordForm.type = res.data.accountVerificationType.length > 0 ? res.data.accountVerificationType[0] : ''
})

onMounted(() => {
    dialogSize()
    useEventListener(window, 'resize', dialogSize)
    if (route.query.type == 'register') state.tab = 'Register'
})
onUnmounted(() => {
    endTiming()
})
</script>
<style scoped>
@import url('https://b.yzcdn.cn/wsc-pc-account/login_b97b5429.css');
</style>
<style scoped lang="scss">
.attention-tips{
    height: 33px;
    font-weight: 600;
    font-size: 24px;
    color: #333333;
    line-height: 33px;
    text-align: center;
    margin-top: 20px;
    font-style: normal;
}
.switch-language {
    position: fixed;
    top: 20px;
    right: 20px;
    z-index: 1;
}


.form-item-icon {
    height: auto;
}

.login {background: #EDF1F4;
    position: absolute;
    top: 0;
    display: flex;
    width: 100vw;
    height: 100vh;
    align-items: center;
    justify-content: center;

    footer {
        font-size: 14px;
        text-align: right;
    }

    .login-box {
        display: flex;
        flex-direction: row-reverse;
        overflow: hidden;
        width: 1320px;
        // background: var(--ba-bg-color-overlay);
        position: absolute;
        left: 0;
        right: 0;
        margin: auto;
        z-index: 1;
        box-sizing: border-box;
        padding: 66px 30px;
        font-size: 18px;

        &::after {
            content: "";
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            filter: blur(10px);
            z-index: -1;
        }
    }

    .head {
        background: #162cb0;
        border-radius: 20px;
        width: 660px;
        img {
            display: block;
            width: 430px;
            margin: 0 auto;
            user-select: none;
        }
    }

    .form {
        position: relative;
        border-radius: 20px;
        width: 660px;
        height: 660px;
        background: #FFFFFF;
        right: -40px;

        .profile-avatar {
            display: block;
            position: absolute;
            height: 100px;
            width: 100px;
            border-radius: 50%;
            border: 4px solid var(--ba-bg-color-overlay);
            top: -50px;
            right: calc(50% - 50px);
            z-index: 2;
            user-select: none;
        }

        .content {
            padding: 100px 40px 40px 40px;
        }

        .submit-button {
            width: 100%;
            letter-spacing: 2px;
            font-weight: 300;
            margin-top: 15px;
            --el-button-bg-color: var(--el-color-primary);
        }
    }
}

@media screen and (max-width: 720px) {
    .login {
        display: flex;
        align-items: center;
        justify-content: center;

        .login-box {
            width: 340px;
            margin-top: 0;
        }
    }
}

.chang-lang :deep(.el-dropdown-menu__item) {
    justify-content: center;
}

.content :deep(.el-input__prefix) {
    display: flex;
    align-items: center;
}


@media screen and (max-height: 800px) {
    .login .login-box {
        margin-bottom: 0;
    }
}
</style>
